<template>
  <el-dialog
    :title="isEdit ? '编辑联系人' : '新增联系人'"
    v-model="dialogVisible"
    width="500px"
    destroy-on-close
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
      </el-form-item>

      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="职位" prop="position">
        <el-input v-model="form.position" placeholder="请输入职位" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
          <el-option label="正常" value="normal" />
          <el-option label="禁用" value="disabled" />
          <el-option label="注销" value="deleted" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { CustomerContact } from '@/store/customer'

// 定义props
const props = defineProps<{
  modelValue: boolean;
  contact: CustomerContact | null;
}>()

// 定义emit
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void;
  (e: 'success', contact: CustomerContact): void;
}>()

// 状态
const loading = ref(false)
const formRef = ref<FormInstance>()

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.contact?.id)

// 表单数据
const form = reactive<{
  contactName: string;
  contactPhone: string;
  email: string;
  position: string;
  status: string;
}>({
  contactName: '',
  contactPhone: '',
  email: '',
  position: '',
  status: 'normal'
})

// 表单验证规则
const rules = reactive<FormRules>({
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 初始化表单数据
const initFormData = () => {
  if (props.contact) {
    Object.assign(form, {
      contactName: props.contact.contactName,
      contactPhone: props.contact.contactPhone,
      email: props.contact.email,
      position: props.contact.position,
      status: props.contact.status
    })
  } else {
    Object.assign(form, {
      contactName: '',
      contactPhone: '',
      email: '',
      position: '',
      status: 'normal'
    })
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const contact: CustomerContact = {
          ...(props.contact || {}),
          contactName: form.contactName,
          contactPhone: form.contactPhone,
          email: form.email,
          position: form.position,
          status: form.status as any
        }
        
        // 如果是新建，生成一个临时ID
        if (!contact.id) {
          contact.id = `temp-${Date.now()}`
        }
        
        emit('success', contact)
        dialogVisible.value = false
      } catch (error) {
        console.error('保存联系人失败', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 对话框关闭
const handleClosed = () => {
  formRef.value?.resetFields()
}

// 监听对话框显示状态
watch(() => dialogVisible.value, (val) => {
  if (val) {
    initFormData()
  }
})
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>